import { initialCanvas, renderImg } from "@/views/welcome/utils/videoFn";

const viodeWebSocket = (url, vidUrl, canvas, Width, Height) => {
  const webSocket = new WebSocket(url, vidUrl);
  webSocket.onopen = () => {
    console.log("连接成功");
  };
  webSocket.onmessage = (res: any) => {
    // 创建一个FileReader对象
    const reader = new FileReader();
    reader.onload = function (event: ProgressEvent<FileReader>) {
      // 读取的结果作为Uint8Array存储在arrayBuffer属性中
      const uint8Array = new Uint8Array(event.target.result as ArrayBuffer);
      if (uint8Array.length === 16) {
        Width = getInt32(uint8Array.subarray(0, 4));
        Height = getInt32(uint8Array.subarray(4, 8));
        initialCanvas(canvas, Width, Height);
        console.log("收到视频宽高信息", Width, Height);
        return;
      }
      if (Width === 0 || Height === 0) {
        console.log("宽高未获取到");
        return;
      }
      if (uint8Array.length !== (Width * Height * 3) / 2) {
        console.log("错误的数据长度");
        return;
      }
      renderImg(canvas, Width, Height, uint8Array);
    };
    reader.readAsArrayBuffer(res.data);
  };

  webSocket.onclose = () => {
    console.log("连接关闭");
  };

  webSocket.onerror = (error: any) => {
    console.log("连接错误!", error);
  };

  return webSocket;
};
/**
 *
 * @param 获取服务端发过来的视频宽高。
 */
const getInt32 = uint8Array => {
  if (uint8Array instanceof Uint8Array) {
    const uint32Array = new Uint32Array(1);
    uint32Array[0] =
      uint8Array[0] |
      (uint8Array[1] << 8) |
      (uint8Array[2] << 16) |
      (uint8Array[3] << 24);
    return uint32Array[0];
  }
  return 0;
};

export default viodeWebSocket;
